package org.budo.support.itext.pdf.renderer;

import java.io.File;
import java.io.OutputStream;

import org.budo.support.itext.pdf.renderer.factory.BudoITextPdfRendererFactory;
import org.budo.support.lang.util.IoUtil;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;

/**
 * @author lmw
 */
public class BudoITextPdfRenderer extends ITextRenderer {
    private Resource[] fonts;

    public BudoITextPdfRenderer withDocumentFromString(String content) {
        this.setDocumentFromString(content);
        return this;
    }

    public BudoITextPdfRenderer withSharedContextBaseURL(String baseUrl) {
        this.getSharedContext().setBaseURL(baseUrl);
        return this;
    }

    public BudoITextPdfRenderer doLayout() {
        this.layout();
        return this;
    }

    @Override
    public void createPDF(OutputStream os) throws DocumentException {
        this.assertFontFileInTmp();

        super.createPDF(os);
    }

    /**
     * 确保字体文件在tmp里面，如果没有就从classpath复制过去
     */
    private void assertFontFileInTmp() {
        try {
            for (Resource font : this.getFonts()) {
                // 是绝对路径文件配置
                if (ResourceUtils.URL_PROTOCOL_FILE.equals(font.getURL().getProtocol())) {
                    continue;
                }

                // 可能是ClassPath路径配置
                File file = new File(BudoITextPdfRendererFactory.FONTS_TMP_DIR, font.getFilename()); // 对应的临时文件路径
                if (file.exists()) {
                    continue; // 临时文件存在
                }

                // 临时文件不存在，写临时文件
                IoUtil.write(font.getInputStream(), file);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public Resource[] getFonts() {
        return this.fonts;
    }

    public void setFonts(Resource[] fonts) {
        this.fonts = fonts;
    }
}